import axios from 'axios'
const instance = axios.create({
  timeout: 20000
})
// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    const token = localStorage.getItem('token')
    config.headers.Authorization = 'Bearer ' + token
    // 在发送请求之前做些什么
    return config
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    // 对响应数据做点什么
    return response
  },
  function (error) {
    // 对响应错误做点什么
    const code = error.response.status
    switch (code) {
      case 400:
        console.log('请求错误')
        break
      case 401:
        window.location.href = '/login'
        console.log('未授权')
        break
      case 403:
        console.log('禁止访问')
        break
      case 404:
        console.log('页面资源未找到')
        break
      case 500:
        console.log('内部服务器错误')
        break
      case 502:
        console.log('网关错误')
        break
      case 503:
        console.log('服务部可用')
        break
      case 504:
        console.log('网关超时')
        break
      default:
        break
    }

    return Promise.reject(error)
  }
)

export const get = (url: string, params?: string) => {
  return instance.get(url, { params })
}

export const post = (url: string, data?: string) => {
  return instance.post(url, data)
}

export default instance
